package controllers

import (
	//"bufio"
	"fmt"
	//"io"
	//"io/ioutil"
	"log"
	//"net/http"
	"strings"
	m "xwaf_admin/models"

	//admlib "xwaf_admin/xadmin/src/lib"

	"github.com/tidwall/gjson"
)

type WafRiskIpController struct {
	CommonController
}

//列表/xwaf/riskip/v1/List
func (this *WafRiskIpController) List() {
	is_malicious := this.GetString("is_malicious")
	ip := this.GetString("ip")
	id, _ := this.GetInt64("id")
	page, _ := this.GetInt64("page")
	page_size, _ := this.GetInt64("limit")
	var tag, riskType string
	var is_autoAdd bool
	if this.Ctx.Request.Method == "POST" {
		gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)
		tag = gp.Get("tag").String()
		ip = gp.Get("ip").String()
		is_autoAdd = gp.Get("is_autoAdd").Bool()
		riskType = gp.Get("risk_type").String()
		is_malicious = gp.Get("is_malicious").String()
	}
	ipseg := strings.Split(ip, ".")
	if ip != "" && len(ipseg) < 3 {
		this.Ctx.WriteString(`{"code":-1,"msg":"errorIp"}`)
		return
	}
	datas, count := m.GetXf_waf_riskipList(is_malicious, tag, ip, id, page, page_size)
	if ip != "" && len(ipseg) == 4 && is_autoAdd {
		var respIpArry []string
		for _, vv := range datas {
			respIpArry = append(respIpArry, vv.Ip)
		}
		ipseg3 := ipseg[0] + "." + ipseg[1] + "." + ipseg[2]
		//ip和c段IP都不在列表中
		if !m.IsExistInArray(respIpArry, ip) && !m.IsExistInArray(respIpArry, ipseg3) {
			u := m.Xf_waf_riskip{}
			u.Ip = ip
			u.Risk_type = riskType
			u.City = m.GetIpCity(ip)

			isMalicious, tag, updateTime, _ := m.QueryRiskIp(ip)
			u.Tag = tag
			u.Is_malicious = isMalicious
			u.Updatetime = updateTime

			if m.JudgeTrustIpFromFile(ip) {
				u.Remarks = "信任ip"
				u.Is_malicious = "false"
				u.Tag = fmt.Sprintf("%s,OtherTrustIP", u.Tag)
				u.Risk_type = "trust"
			}

			if iswhite, msg := m.JudgeWhiteIp(ip); iswhite {
				log.Printf("[WARN] WhiteIp no need add:%s\n", msg)
				this.Ctx.WriteString(`{"code":-1,"msg":"whiteIp"}`)
				return
			}
			id, err := m.AddXf_waf_riskip(&u)
			if err == nil && id > 0 {
				log.Printf("[INFO] Add Reskip success\n")
				this.Ctx.WriteString(`{"code":-1,"msg":"error"}`)
				return
			} else {
				log.Printf("[ERROR] Add Reskip fail")
				this.Ctx.WriteString(`{"code":-1,"msg":"error"}`)
				return
			}

			this.Ctx.WriteString(`{"code":-1,"msg":"error"}`)
			return
		}
	}
	this.Data["json"] = &map[string]interface{}{"code": 0, "msg": "", "count": count, "data": &datas}
	this.ServeJSON()
}

func (this *WafRiskIpController) Iplist() {
	cfgv := this.GetString("cfgv") //用于判断是第一次加载，后续获取变动的IP列表。

	AuthToken := this.Ctx.Request.Header.Get("Auth-Token")
	if AuthToken != ApiToken {
		this.Data["json"] = &map[string]interface{}{"code": -1, "msg": "ApiTokenFail", "count": 0}
		this.ServeJSON()
		return
	}

	datas, count := m.GetRiskIp(cfgv)
	this.Data["json"] = &map[string]interface{}{"code": 0, "msg": "", "count": count, "data": &datas}
	this.ServeJSON()
}

//添加
func (this *WafRiskIpController) Add() {
	u := m.Xf_waf_riskip{}
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")
	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)

	if gp.Get("ip").Exists() {
		u.Ip = gp.Get("ip").String()
		u.Tag = gp.Get("tag").String()
		u.Is_malicious = gp.Get("is_malicious").String()
		u.Risk_type = gp.Get("risk_type").String()
		u.Remarks = gp.Get("remarks").String()
		u.City = m.GetIpCity(u.Ip)
		id, err := m.AddXf_waf_riskip(&u)
		if err == nil && id > 0 {
			log.Printf("[INFO] Add success")
			this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		} else {
			log.Printf("[ERROR] Add Fail:%s", err)
			this.Ctx.WriteString(`{"code":-1,"msg":"error"}`)
		}
	} else {
		this.Data["json"] = &map[string]interface{}{"code": -1, "msg": "bodyParseFail"}
		this.ServeJSON()
	}
}

// //删除
func (this *WafRiskIpController) Del() {
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

	Id, _ := this.GetInt64("id")
	respid, err := m.DelRiskIpById(Id)
	if err == nil && respid > 0 {
		log.Printf("[INFO] Delsuccess")
		this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
	} else {
		log.Printf("[ERROR] Del Error:%s\n", err.Error())
		this.Ctx.WriteString(`{"code":-1,"msg":"Error"}`)
	}
}

func (this *WafRiskIpController) Edit() {
	id := this.GetString("id")
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")
	gp := gjson.ParseBytes(this.Ctx.Input.RequestBody)

	if gp.Get("name").Exists() {
		name := gp.Get("name").String()
		value := gp.Get("value").String()
		_, err := m.EditRiskIp(id, name, value)
		if err == nil {
			this.Ctx.WriteString(`{"code":0,"msg":"success"}`)
		} else {
			log.Printf("[ERROR] update blackip Fail:%s\n", err)
			this.Ctx.WriteString(fmt.Sprintf(`{"code":-1,"msg":"%s"}`, err.Error()))
		}
	} else {
		this.Ctx.WriteString(`{"code":-1,"msg":"bodyParseFail"}`)
	}
}

//
// func (this *WafRiskIpController) JudgeOtherTrustIp() {
// 	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
// 	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")
// 	ip := this.GetString("ip")
// 	resp := m.JudgeTrustIpFromFile(ip)
// 	this.Ctx.WriteString(fmt.Sprintf("%v", resp))
// }

//临时更新城市信息到city字段
func (this *WafRiskIpController) UpdateCityByIp() {
	this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json;charset=utf-8")

	ip := this.GetString("ip")
	num, err := m.UpdateCityByIp(ip)
	if err == nil {
		this.Ctx.WriteString(fmt.Sprintf(`{"code":0,"msg":"success:%d"}`, num))
	} else {
		this.Ctx.WriteString(fmt.Sprintf(`{"code":-1,"msg":"%s"}`, err.Error()))
	}
}
